package com.example.chirdrenserver.controller.AdminController;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.chirdrenserver.Authority.Authority;
import com.example.chirdrenserver.Holder.UserHolder;
import com.example.chirdrenserver.Pojo.dto.admin.*;
import com.example.chirdrenserver.Pojo.entity.File;
import com.example.chirdrenserver.Pojo.entity.User;
import com.example.chirdrenserver.Pojo.vo.UserInfoVO;
import com.example.chirdrenserver.Pojo.vo.admin.*;
import com.example.chirdrenserver.Service.AdminService.UserService;
import com.example.chirdrenserver.Service.FileService;
import com.example.chirdrenserver.Utils.Result;
import com.example.chirdrenserver.Utils.AdminUserConverter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/users")
public class AdminUserController {

    private final UserService userService;

    @Autowired
    FileService fileService;

    @Autowired
    public AdminUserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping
    @Authority(authority= "permission:user")
    public Result<AdminUserVO> createUser(@Validated @RequestBody AdminCreateUserDTO dto) {
        User user = AdminUserConverter.toEntity(dto);
        boolean success = userService.save(user);
        return success ?
                Result.success(AdminUserConverter.toVO(user)) :
                Result.error("创建用户失败");
    }

    @PutMapping("/{id}")
    @Authority(authority= "permission:user")
    public Result<AdminUserVO> updateUser(
            @PathVariable Long id,
            @Validated @RequestBody AdminUserUpdateDTO dto) {

        User user = userService.getById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }

        User updatedUser = AdminUserConverter.toEntity(dto, user);
        updatedUser.setAvatarFileKey(dto.getAvatar());
        boolean success = userService.updateById(updatedUser);
        return success ?
                Result.success(AdminUserConverter.toVO(updatedUser)) :
                Result.error("更新用户失败");
    }

    @DeleteMapping("/{id}")
    @Authority(authority= "permission:user")
    public Result<Void> deleteUser(@PathVariable Long id) {
        boolean success = userService.deleteUser(id);
        return success ? Result.success() : Result.error("删除用户失败");
    }

    @GetMapping("/page")
    @Authority(authority= "permission:user")
    public Result<AdminUserPageVO<AdminUserVO>> getUserPage(
            @Validated AdminUserQueryDTO queryDTO) {

        IPage<User> userPage = userService.getUserPage(queryDTO);
        IPage<AdminUserVO> voPage = userPage.convert(AdminUserConverter::toVO);
        AdminUserPageVO<AdminUserVO> pageVO = new AdminUserPageVO<>(voPage);

        return Result.success(pageVO);
    }

    @GetMapping("/list")
    @Authority(authority= "permission:user")
    public Result<List<AdminUserVO>> getAllUsers() {
        List<User> users = userService.list();
        List<Long> userIds = users.stream()
                .map(User::getId)
                .collect(Collectors.toList());

        Map<Long, List<Integer>> userRolesMap = userService.getUserRoleIdsBatch(userIds);

        List<AdminUserVO> userVOs = users.stream()
                .map(user -> {
                    List<Integer> roles = userRolesMap.getOrDefault(user.getId(), Collections.emptyList());
                    return AdminUserConverter.toVOWithRoles(user, roles);
                })
                .collect(Collectors.toList());

        return Result.success(userVOs);
    }

    @GetMapping("/{identifier}")
    @Authority(authority= "permission:user")
        public Result<AdminUserVO> getUserDetail(@PathVariable String identifier) {
            User user = findUserByIdentifier(identifier);
            if (user != null) {
                List<Integer> roles = userService.getUserRoleIds(user.getId());
                return Result.success(AdminUserConverter.toVOWithRoles(user, roles));
            }
            return Result.error("用户不存在");
    }

    private User findUserByIdentifier(String identifier) {
        try {
            Long id = Long.parseLong(identifier);
            return userService.getUserById(id);
        } catch (NumberFormatException e) {
            return userService.getUserByNickname(identifier);
        }
    }

    @PostMapping("/{userId}/roles")
    @Authority(authority= "permission:user")
    public Result<Void> assignRoles(
            @PathVariable Long userId,
            @RequestBody List<Integer> roleIds) {

        boolean success = userService.assignRoles(userId, roleIds);
        return success ?
                Result.success() :
                Result.error("角色分配失败");
    }

    @GetMapping("/{userId}/roles")
    @Authority(authority= "permission:user")
    public Result<List<Integer>> getUserRoles(@PathVariable Long userId) {
        List<Integer> roleIds = userService.getUserRoleIds(userId);
        return Result.success(roleIds);
    }

    @PostMapping("/info")
    public Result getLoginUserInfo()
    {
        User user = userService.getById((Long) UserHolder.get());
        File file = fileService.getOne(new LambdaQueryWrapper<File>().eq(File::getFileKey, user.getAvatarFileKey()));
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(user, userInfoVO);
        if(ObjectUtil.isEmpty(file))
        {
            return Result.success(userInfoVO);
        }
        BeanUtils.copyProperties(file, userInfoVO);
        return Result.success(userInfoVO);
    }
}